#!/usr/bin/python
# -*- coding: utf-8 -*-
# Guguk Project!

# Taha Doğan Güneş
# tdgunes@gmail.org


import time, sys, os, datetime
try:
    from PyQt4.QtCore import *
    from PyQt4.QtGui import *
except ImportError:
    print 'PyQt4 kütüphanesi bulunmamadı!'
    sys.exit(1)
PHONON = True
#PHONON = False
#import pygplayer

try:
    from PyQt4.phonon import Phonon
except ImportError:
    print 'Phonon kütüphanesi bulunamadı!\nPyGame kütüphanesi kullanılacak!'
    try:
        PHONON = False
        import pygplayer
    except ImportError:
        print 'PyGame kütüphanesi bulunamdı!\nTamamen kapatılıyor!'
        sys.exit(1)

try:
    import guguk_rc
except ImportError:
    print 'Derleniyor'
    os.chdir(os.getcwd()+'/src')
    os.sys.path.append('./')
    os.system('pyrcc4 guguk.qrc -o guguk_rc.py')
    print 'Yeniden açın!'
    sys.exit(1)
ABOUT = """
<p><font color=black size=30><b>Guguk 0.1</b><font></p>
<p>Bir Guguklu Saat</p>
<p></p>
<p>Taha Dogan Gunes tdgunes@gmail.com</p>
<p>Lisans: GPLv3</p>
<p>Web Site: http://code.google.com/p/guguk</p>
"""


class SoundObject(QThread):
    def __init__(self,parent = None):
        QThread.__init__(self,parent)
        self.waitSecs = None #msecs
        self.process = True
        self.timer = QTimer()
        self.timer2 = QTimer()
        #Some timer signals to make it run perfectly
        self.connect(self.timer, SIGNAL('timeout()'), self.preRun)
        self.connect(self.timer2, SIGNAL('timeout()'), self.play)
        self.y = 0
        self.say = 1
    def play(self): #Play function
        if self.process:
            print 'Çalıyor'
            self.timer2.stop()
            self.say += 1
            if PHONON:
                self.mediaObject.play()
            else:
                pygplayer.play(os.getcwd()+'/src/data/cuck.wav')
            self.y += 1
        if self.y == (self.hour+1): # To stop the process and starting the waiting
            print '1 saat sonra görüşürüz'
            self.x = 0
            self.y = 0
            self.say = 1
            self.process = False
            self.run()
        else:
            self.preRun()

    def preRun(self): #Where you come from def run
        if self.process:
            self.timer.stop()
            self.x = (self.hour + 1)
            print self.say, 'çaldı!'
            while self.x>0:
                self.define()
                self.x = self.x - 1
                self.timer2.start(750)
            
    def run(self): #Where everthing starts
        self.emit(SIGNAL('donePlay()'))
        self.process=True
        self.calculateSec()
        print 'Bekleme sürecine girildi.'
        self.timer.start(self.waitSecs)
    def define(self): #To play it you need to define it everytime
        if PHONON:
            self.mediaObject = Phonon.MediaObject(self)
            self.audioOutput = Phonon.AudioOutput(Phonon.MusicCategory, self)
            Phonon.createPath(self.mediaObject, self.audioOutput)
            self.sourcePath = Phonon.MediaSource(os.getcwd() +'/src/data/cuck.mp3')
            self.mediaObject.setCurrentSource(self.sourcePath)
        else:
            pass
    def timeUpdate(self):
        print 'Yeni zaman alınıyor'
        self.now = datetime.datetime.now()
        self.second = self.now.second
        self.minute = self.now.minute
        self.hour = self.now.hour
    def calculateSec(self):
        self.timeUpdate()
        print 'Toplam milisaniyeler hesaplanıyor'
        newsecs = (self.hour+1)*3600
        nowsecs = self.hour*3600 + self.minute*60 + self.second
        #self.waitSecs = 6000 
        self.waitSecs = (newsecs - nowsecs)*1000
        if self.hour > 12:
            self.hour -= 12
        print 'Msecs:',self.waitSecs

       
class TrayIcon(QSystemTrayIcon):
    def __init__(self, parent=None):
        super(TrayIcon, self).__init__(parent)
        #New logos are OK! for now
		#':/images/bad.svg'
        self.icon = QIcon(':/data/guguk.png')
        self.icon2 = QIcon(':/data/guguk2.png')
      
        self.setIcon(self.icon2)

class TrayObject(QWidget):
    def __init__(self, parent=None):
        super(TrayObject, self).__init__(parent)
        self.trayicon = TrayIcon()
        self.sound = SoundObject() 
    def start(self):
        self.trayicon.setIcon(self.trayicon.icon)
        self.sound.run()
    def show(self):
        self.trayicon.show() 
    def pause(self):
        self.trayicon.setIcon(self.trayicon.icon2)
        print 'Durdu!'
        self.sound.process = False
        self.sound.quit()
    def message(self):
        print 'SIGNAL alındı!'
        now = datetime.datetime.now()
        str2 = 'Saat: %s:%s:%s' % (now.hour, now.minute, now.second)
        self.trayicon.showMessage(u'Guguk!', str2)
    def about(self):
        self.trayicon.showMessage(u'Hakkında', 'Guguk 0.1\n---------\nBir Guguklu Saat\n\nTaha Dogan Gunes\nLisans: GPLv3\n\ncode.google.com/p/guguk')
def run():
    #FIXE make it translatable
    app = QApplication(sys.argv)
    trayicon = TrayObject()


    menu = QMenu()
    actionStart = QAction(trayicon.trayicon.icon, u"Gugukla", menu)
    actionPause = QAction(trayicon.trayicon.icon2,u"Durdur", menu)
    actionAbout = QAction(u'Hakkında', menu)
    actionQuit = QAction(u"Çıkış", menu)
    

    menu.addAction(actionStart)
    menu.addAction(actionPause)
    menu.addSeparator()
    menu.addAction(actionAbout)
    menu.addAction(actionQuit)
    trayicon.trayicon.setContextMenu(menu)

    QObject.connect(trayicon.sound, SIGNAL('donePlay()'), trayicon.message)
    QObject.connect(actionQuit, SIGNAL("activated()"), app.quit)
    QObject.connect(actionAbout, SIGNAL('activated()'), trayicon.about)
    QObject.connect(actionStart, SIGNAL("activated()"), trayicon.start)
    QObject.connect(actionPause, SIGNAL("activated()"), trayicon.pause)
    
    trayicon.show()
    sys.exit(app.exec_())
    


